package cn.edu.hqu.cst.android.sensor;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;

public class Compass extends AppCompatActivity implements SensorEventListener {
    // 定义显示指南针的图片
    ImageView image_compass;
    // 记录指南针图片转过的角度
    float currentDegree = 0f;
    // 定义Sensor管理器
    SensorManager sensor_compass;
    private SensorListener listener = new SensorListener() {
        @Override
        public void onSensorChanged(int sensor, float[] values) {

        }

        @Override
        public void onAccuracyChanged(int sensor, int accuracy) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);
        //设置返回
        Button back = findViewById(R.id.backpage_com);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Compass.this,MainActivity.class);
                startActivity(i);
            }
        });
        // 获取界面中显示指南针的图片
        image_compass = findViewById(R.id.compass);
        image_compass.setKeepScreenOn(true);
        // 获取传感器管理服务
        sensor_compass = (SensorManager) getSystemService(SENSOR_SERVICE);

        sensor_compass.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 为系统的方向传感器注册监听器
        sensor_compass.registerListener(this,
                sensor_compass.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onPause() {
        // 取消注册
        sensor_compass.unregisterListener(this);
        super.onPause();
    }

    @Override
    protected void onStop(){
        // 取消注册
        sensor_compass.unregisterListener(this);
        super.onStop();
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float degree = event.values[0];// 存放了方向值 90
        RotateAnimation animation = new RotateAnimation(currentDegree, -degree,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(200);
        image_compass.startAnimation(animation);
        currentDegree = -degree;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
